<template>
  <el-button plain @click="open"> Use HTML String</el-button>
  <el-upload
      ref="uploadRef"
      class="upload-demo"
      :auto-upload="false"
      :limit="5"
      :on-change="uploadFile"
      multiple
  >
    <template #trigger>
      <el-button type="primary">select file</el-button>
    </template>

    <el-button class="ml-3" type="success" @click="submitUpload">
      upload to server
    </el-button>

    <template #tip>
      <div class="el-upload__tip">
        jpg/png files with a size less than 500kb
      </div>
    </template>
  </el-upload>

  <div class="demo-image__lazy">
    <el-image v-for="url in urls" :key="url" :src="url" lazy/>
  </div>

</template>

<script lang="ts" setup>
import {error} from "../../utils/messageUtil";
import {onMounted, onUnmounted, ref} from "vue";
import {MessageDto, MessageType, send, SessionType, webSocket, webSocketLink} from "../../utils/webSocket"
import {FileType, localKey, userInfo} from "../../utils/constant";
import type {UploadFile, UploadFiles, UploadInstance} from 'element-plus'
import {upload} from "../../service/FileApi";
import {ping} from "../../service/AccountApi";

let timer:NodeJS.Timer;

let keepConnection:any = localStorage.getItem(localKey.keepConnection);

//页面加载之后 绑定websocket
onMounted(() => {

  webSocketLink(userInfo().id)

  //主页每隔15 分钟去请求一下
  timer = setInterval(()=>{
    ping(null)
  }, 1050 * (keepConnection))
})

//关闭webSocket
onUnmounted(()=> {
  webSocket.close();
  clearInterval(timer);
})

const open = () => {
  let messageDte: MessageDto = {
    sendUserSocketDto: {
      userId: userInfo().id,
      name: userInfo().name
    },
    acceptUserSocketDto: {
      userId: 'a4025cb1-7df6-413f-b102-38ea28574e07',
      name: '我的小号'
    },
    message: '<a href="http://www.baidu.com">百度</a>',
    type: MessageType.HTML,
    sessionType: SessionType.ALONG
  }
  send(messageDte)
};

const uploadRef = ref<UploadInstance>()

const fileRo: any = {
  multipartFiles: [],
  fileType: FileType.OTHER
}

const uploadFile = (uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  fileRo.multipartFiles.push(uploadFile.raw)
  console.log(fileRo)
}

const submitUpload = () => {
  console.log(fileRo)
  upload(fileRo).then(d => {
    console.log(d.data)

    if (d.data.code != '200') {
      error(d.data.message)
    }else{
      d.data.date.tokenUrls.forEach((url:string)=>{
        urls.value?.push(url)
      })
    }

  }).catch(e => {
    console.log(e)
    error("网络异常")
  })
}

const urls = ref<string[]>([])
</script>

<style scoped>
.demo-image__lazy {
  height: 400px;
  overflow-y: auto;
}

.demo-image__lazy .el-image {
  display: block;
  min-height: 200px;
  margin-bottom: 10px;
}

.demo-image__lazy .el-image:last-child {
  margin-bottom: 0;
}
</style>